// Canvas血量/护盾UI管理器
// 在canvas右上角绘制血量和护盾的组合UI
import { TimeManager } from './TimeManager.js';

export class CanvasHealthUI {
    constructor(maxHealth = 5) {
        this.maxHealth = maxHealth;
        this.currentHealth = maxHealth;
        this.displayHealth = maxHealth; // 用于过渡动画的血量
        this.transitionHealth = maxHealth; // 过渡血条显示的血量
        
        // 护盾状态
        this.shieldCharges = 0;
        this.displayShield = 0; // 用于过渡动画的护盾
        this.transitionShield = 0; // 过渡护盾显示
        
        // UI位置和尺寸
        this.barWidth = 200;
        this.barHeight = 25;
        this.margin = 20; // 距离边缘的距离
        this.cornerRadius = 5;
        
        // 过渡动画控制
        this.isTransitioning = false;
        this.isShieldTransitioning = false;
        this.transitionStartTime = 0;
        this.shieldTransitionStartTime = 0;
        this.transitionDuration = 1200; // 过渡动画持续时间（毫秒）
        this.transitionDelay = 400; // 过渡动画开始前的延迟（毫秒）
        
        // 视觉特效
        this.pulsePhase = 0;
        this.glowIntensity = 0;
        this.fadeAlpha = 1.0; // 整体UI的透明度
        this.showUI = true; // 是否显示UI
        this.fadeOutTime = 0; // 淡出计时器
        this.fadeOutDuration = 2000; // 2秒后开始淡出
    }
    
    // 设置最大血量
    setMaxHealth(maxHealth) {
        this.maxHealth = maxHealth;
        this.currentHealth = Math.min(this.currentHealth, maxHealth);
        this.displayHealth = this.currentHealth;
        this.transitionHealth = this.currentHealth;
    }
    
    // 设置当前血量
    setCurrentHealth(health) {
        const newHealth = Math.max(0, Math.min(this.maxHealth, health));
        
        if (newHealth !== this.currentHealth) {
            const oldHealth = this.currentHealth;
            this.currentHealth = newHealth;
            
            // 如果是减血，启动过渡动画
            if (newHealth < oldHealth) {
                this.startHealthTransition();
            } else {
                // 如果是加血，立即更新所有值
                this.displayHealth = newHealth;
                this.transitionHealth = newHealth;
                this.isTransitioning = false;
            }
            
            this.showUI = true;
            this.fadeOutTime = 0;
            this.fadeAlpha = 1.0;
        }
    }
    
    // 设置护盾充能数
    setShieldCharges(charges) {
        const newCharges = Math.max(0, Math.min(3, charges)); // 最多3层护盾
        
        if (newCharges !== this.shieldCharges) {
            const oldCharges = this.shieldCharges;
            this.shieldCharges = newCharges;
            
            // 如果护盾减少，启动护盾过渡动画
            if (newCharges < oldCharges) {
                this.startShieldTransition();
            } else {
                // 如果护盾增加，立即更新
                this.displayShield = newCharges;
                this.transitionShield = newCharges;
                this.isShieldTransitioning = false;
            }
            
            this.showUI = true;
            this.fadeOutTime = 0;
            this.fadeAlpha = 1.0;
        }
    }
    
    // 启动血量过渡动画
    startHealthTransition() {
        this.isTransitioning = true;
        this.transitionStartTime = Date.now();
        
        // 立即更新当前血条显示
        this.displayHealth = this.currentHealth;
        // 过渡血条暂时保持原来的值，稍后开始缓慢减少
    }
    
    // 启动护盾过渡动画
    startShieldTransition() {
        this.isShieldTransitioning = true;
        this.shieldTransitionStartTime = Date.now();
        
        // 立即更新当前护盾显示
        this.displayShield = this.shieldCharges;
        // 过渡护盾暂时保持原来的值，稍后开始缓慢减少
    }
    
    // 更新UI状态
    update(deltaTime) {
        // 更新视觉特效
        this.pulsePhase = TimeManager.updatePhase(this.pulsePhase, deltaTime, 3);
        
        // 更新血量过渡动画
        if (this.isTransitioning) {
            const currentTime = Date.now();
            const elapsed = currentTime - this.transitionStartTime;
            
            if (elapsed >= this.transitionDelay) {
                // 开始过渡动画
                const transitionProgress = Math.min(1, (elapsed - this.transitionDelay) / this.transitionDuration);
                const easedProgress = this.easeOutCubic(transitionProgress);
                
                // 平滑减少过渡血条
                const startValue = this.transitionHealth || this.currentHealth + 1;
                this.transitionHealth = startValue - (startValue - this.currentHealth) * easedProgress;
                
                if (transitionProgress >= 1) {
                    this.isTransitioning = false;
                    this.transitionHealth = this.currentHealth;
                }
            }
        }
        
        // 更新护盾过渡动画
        if (this.isShieldTransitioning) {
            const currentTime = Date.now();
            const elapsed = currentTime - this.shieldTransitionStartTime;
            
            if (elapsed >= this.transitionDelay * 0.5) { // 护盾过渡更快
                const transitionProgress = Math.min(1, (elapsed - this.transitionDelay * 0.5) / (this.transitionDuration * 0.8));
                const easedProgress = this.easeOutCubic(transitionProgress);
                
                // 平滑减少过渡护盾
                const startValue = this.transitionShield || this.shieldCharges + 1;
                this.transitionShield = startValue - (startValue - this.shieldCharges) * easedProgress;
                
                if (transitionProgress >= 1) {
                    this.isShieldTransitioning = false;
                    this.transitionShield = this.shieldCharges;
                }
            }
        }
        
        // 处理UI淡出效果
        if (this.showUI && this.currentHealth === this.maxHealth && this.shieldCharges === 0) {
            this.fadeOutTime += deltaTime;
            if (this.fadeOutTime >= this.fadeOutDuration) {
                // 开始淡出
                const fadeProgress = Math.min(1, (this.fadeOutTime - this.fadeOutDuration) / 1000); // 1秒淡出
                this.fadeAlpha = 1.0 - this.easeInCubic(fadeProgress);
                
                if (this.fadeAlpha <= 0) {
                    this.showUI = false;
                }
            }
        }
    }
    
    // 缓动函数
    easeOutCubic(t) {
        return 1 - Math.pow(1 - t, 3);
    }
    
    easeInCubic(t) {
        return t * t * t;
    }
    
    // 减少血量
    takeDamage(damage = 1) {
        this.setCurrentHealth(this.currentHealth - damage);
    }
    
    // 恢复血量
    heal(amount = 1) {
        this.setCurrentHealth(this.currentHealth + amount);
    }
    
    // 检查是否死亡
    isDead() {
        return this.currentHealth <= 0;
    }
    
    // 渲染UI
    render(ctx, canvasWidth, canvasHeight) {
        if (!this.showUI || this.fadeAlpha <= 0) return;
        
        ctx.save();
        
        // 应用整体透明度
        ctx.globalAlpha = this.fadeAlpha;
        
        // 计算UI位置（右上角）
        const uiX = canvasWidth - this.barWidth - this.margin;
        const uiY = this.margin;
        
        // 绘制背景底板
        this.renderBackground(ctx, uiX, uiY);
        
        // 绘制血量槽
        this.renderHealthBar(ctx, uiX, uiY);
        
        // 绘制护盾覆盖层
        if (this.shieldCharges > 0 || this.isShieldTransitioning) {
            this.renderShieldOverlay(ctx, uiX, uiY);
        }
        
        // 绘制边框和装饰
        this.renderBorder(ctx, uiX, uiY);
        
        // 绘制数值文本
        // this.renderText(ctx, uiX, uiY);
        
        ctx.restore();
    }
    
    // 绘制背景底板
    renderBackground(ctx, x, y) {
        // 外层发光边框
        ctx.shadowBlur = 15;
        ctx.shadowColor = 'rgba(255, 255, 255, 0.3)';
        
        // 背景渐变
        const bgGradient = ctx.createLinearGradient(x, y, x, y + this.barHeight);
        bgGradient.addColorStop(0, 'rgba(20, 20, 30, 0.9)');
        bgGradient.addColorStop(0.5, 'rgba(30, 30, 40, 0.9)');
        bgGradient.addColorStop(1, 'rgba(20, 20, 30, 0.9)');
        
        ctx.fillStyle = bgGradient;
        this.roundRect(ctx, x - 2, y - 2, this.barWidth + 4, this.barHeight + 4, this.cornerRadius + 2);
        ctx.fill();
        
        // 重置阴影
        ctx.shadowBlur = 0;
    }
    
    // 绘制血量槽
    renderHealthBar(ctx, x, y) {
        // 血量槽背景
        ctx.fillStyle = 'rgba(40, 20, 20, 0.8)';
        this.roundRect(ctx, x, y, this.barWidth, this.barHeight, this.cornerRadius);
        ctx.fill();
        
        // 过渡血量条（在后面）
        if (this.transitionHealth > this.displayHealth) {
            const transitionPercent = this.transitionHealth / this.maxHealth;
            const transitionWidth = (this.barWidth - 4) * transitionPercent;
            
            // 过渡血量渐变（橙黄色）
            // const transitionGradient = ctx.createLinearGradient(x + 2, y + 2, x + 2 + transitionWidth, y + 2);
            // transitionGradient.addColorStop(0, 'rgba(255, 255, 100, 0.8)');
            // transitionGradient.addColorStop(0.5, 'rgba(255, 200, 50, 0.8)');
            // transitionGradient.addColorStop(1, '#ea2828');
            
            ctx.fillStyle = '#ea2828';
            this.roundRect(ctx, x + 2, y + 2, transitionWidth, this.barHeight - 4, this.cornerRadius - 2);
            ctx.fill();
        }
        
        // 当前血量条（在前面）
        const healthPercent = this.displayHealth / this.maxHealth;
        const healthWidth = (this.barWidth - 4) * healthPercent;
        
        if (healthWidth > 0) {
            // 血量颜色根据百分比变化
            let healthGradient;
            if (healthPercent > 0.6) {
                healthGradient = ctx.createLinearGradient(x + 2, y + 2, x + 2 + healthWidth, y + 2);
                healthGradient.addColorStop(0, '#44ff44');
                healthGradient.addColorStop(1, '#66ff66');
            } else if (healthPercent > 0.3) {
                healthGradient = ctx.createLinearGradient(x + 2, y + 2, x + 2 + healthWidth, y + 2);
                healthGradient.addColorStop(0, '#ffff44');
                healthGradient.addColorStop(1, '#ffaa44');
            } else {
                healthGradient = ctx.createLinearGradient(x + 2, y + 2, x + 2 + healthWidth, y + 2);
                healthGradient.addColorStop(0, '#ff4444');
                healthGradient.addColorStop(1, '#ff6666');
                
                // 低血量时闪烁效果
                const pulse = 0.7 + Math.sin(this.pulsePhase * 3) * 0.3;
                ctx.globalAlpha *= pulse;
            }
            
            ctx.fillStyle = healthGradient;
            this.roundRect(ctx, x + 2, y + 2, healthWidth, this.barHeight - 4, this.cornerRadius - 2);
            ctx.fill();
            
            // 恢复透明度
            ctx.globalAlpha = this.fadeAlpha;
        }
    }
    
    // 绘制护盾覆盖层
    /**
     *  @type {CanvasRenderingContext2D} ctx
     */
    renderShieldOverlay(ctx, x, y) {
        const maxShield = 3;
        const shieldPercent = Math.max(this.displayShield, this.transitionShield) / maxShield;
        const shieldHeight = (this.barHeight - 4) * 0.4; // 护盾占血槽下半部分的40%
        const shieldY = y + 2 + (this.barHeight - 4) * 0.6; // 在血槽的下半部分
        
        
        // 过渡护盾层
        if (this.transitionShield > this.displayShield) {
            const transitionPercent = this.transitionShield / maxShield;
            const transitionWidth = (this.barWidth - 4) * transitionPercent;
            
            ctx.fillStyle = 'rgba(180, 180, 220, 0.6)';
            this.roundRect(ctx, x + 2, shieldY, transitionWidth, shieldHeight, this.cornerRadius - 2);
            ctx.fill();
        }
        
        // 当前护盾层
        if (this.displayShield > 0) {
            const currentPercent = this.displayShield / maxShield;
            const currentWidth = (this.barWidth - 4) * currentPercent;
            
            // 护盾渐变（半透明白灰色）
            const shieldGradient = ctx.createLinearGradient(x + 2, shieldY, x + 2 + currentWidth, shieldY);
            const pulse = 1;
            shieldGradient.addColorStop(0, `rgba(200, 200, 255, 0.92)`);
            shieldGradient.addColorStop(0.5, `rgba(200, 200, 255, 0.92)`);
            shieldGradient.addColorStop(1, `rgba(200, 200, 255, 0.92)`);
            
            ctx.fillStyle = shieldGradient;
            this.roundRect(ctx, x + 2, shieldY, currentWidth, shieldHeight, this.cornerRadius - 2);
            ctx.fill();
            
            // 护盾边缘光效
            ctx.strokeStyle = `rgba(150, 150, 255, ${pulse})`;
            ctx.lineWidth = 1;
            this.roundRect(ctx, x + 2, shieldY, currentWidth, shieldHeight, this.cornerRadius - 2);
            ctx.stroke();
        }
    }
    
    // 绘制边框
    renderBorder(ctx, x, y) {
        // 主边框
        ctx.strokeStyle = '#666666';
        ctx.lineWidth = 2;
        this.roundRect(ctx, x, y, this.barWidth, this.barHeight, this.cornerRadius);
        ctx.stroke();
        
        // 内边框光效
        const glowPulse = 0.3 + Math.sin(this.pulsePhase) * 0.2;
        ctx.strokeStyle = `rgba(255, 255, 255, ${glowPulse})`;
        ctx.lineWidth = 1;
        this.roundRect(ctx, x + 1, y + 1, this.barWidth - 2, this.barHeight - 2, this.cornerRadius - 1);
        ctx.stroke();
    }
    
    // 绘制文本
    renderText(ctx, x, y) {
        ctx.fillStyle = '#ffffff';
        ctx.font = 'bold 12px Arial';
        ctx.textAlign = 'left';
        ctx.shadowBlur = 2;
        ctx.shadowColor = 'rgba(0, 0, 0, 0.8)';
        
        // 血量文本
        const healthText = `HP: ${Math.ceil(this.currentHealth)}/${this.maxHealth}`;
        ctx.fillText(healthText, x + 8, y + 12);
        
        // 护盾文本（如果有护盾）
        if (this.shieldCharges > 0) {
            ctx.fillStyle = '#aaaaff';
            const shieldText = `护盾: ${this.shieldCharges}`;
            ctx.fillText(shieldText, x + 8, y + this.barHeight - 3);
        }
        
        // 重置阴影
        ctx.shadowBlur = 0;
    }
    
    // 绘制圆角矩形
    roundRect(ctx, x, y, width, height, radius) {
        ctx.beginPath();
        ctx.moveTo(x + radius, y);
        ctx.lineTo(x + width - radius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx.lineTo(x + width, y + height - radius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx.lineTo(x + radius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx.lineTo(x, y + radius);
        ctx.quadraticCurveTo(x, y, x + radius, y);
        ctx.closePath();
    }
    
    // 获取当前血量
    getCurrentHealth() {
        return this.currentHealth;
    }
    
    // 获取最大血量
    getMaxHealth() {
        return this.maxHealth;
    }
}